<template>
  <div class="app-container">
    <!-- 工具栏 start-->
    <!--    <div class="nav-link">-->

    <!--      <template v-for="(item, index) in tabs">-->
    <!--        &lt;!&ndash;<el-button @click="handleToggle(index)" size="medium" :class="{'ntp-btn': true, active: currentIndex==index, warn2: warns.indexOf(index)>-1}">{{item.label}}</el-button>&ndash;&gt;-->
    <!--        <el-button @click="handleToggle(index)" size="medium" :class="{'ntp-btn': true, active: currentIndex==index}">{{ item.label }}</el-button>-->
    <!--      </template>-->

    <!--    </div>-->
    <!-- 工具栏 end-->

    <div class="page-content mt20">
      <!--      <template v-if="info">-->
      <!--        <div class="masks"></div>-->
      <!--      </template>-->

      <el-form :model="createForm" ref="createForm" label-width="150px" size="small">
        <!-- 基本资料 start -->
        <div class="bar">基础资料</div>
        <div class="contents contents1">
          <el-form-item label="供应商类型：" prop="classify_id" :rules="$rule.required">
            <el-select v-model="createForm.classify_id" placeholder="请选择">
              <el-option
                v-for="item in classify"
                :key="item.id"
                :label="item.content"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>

          <div class="row">
            <div class="row-main dfa">
              <el-form-item class="f1" label="供应商名称" prop="name" :rules="$rule.required">
                <!--<el-input placeholder="请输入供应商名称" v-model="createForm.name" :disabled="fact" clearable></el-input>-->
                <template v-if="fact">
                  <el-select
                    v-model="createForm.name"
                    filterable
                    remote
                    placeholder="请输入供应商名称"
                    :remote-method="remoteMethod"
                    @change="supSelectChange"
                    :loading="loading"
                    disabled
                  >
                    <el-option
                      v-for="(item, index) in qxoptions"
                      :key="index"
                      :label="item.label"
                      :value="item.value"
                    ></el-option>
                  </el-select>
                </template>

                <template v-else>
                  <el-input placeholder="请输入供应商名称" v-model="createForm.name" clearable></el-input>
                </template>
              </el-form-item>
            </div>
            <div class="dfa row-aside supname">
              <div class="label">真实性验证</div>
              <el-switch
                @change="changeSwitch"
                v-model="createForm.authenticity"
                :active-value="1"
                :inactive-value="0"
                disabled
              />
            </div>
          </div>

          <el-form-item label="统一社会信用代码" prop="credit_code" :rules="$rule.required">
            <el-input
              placeholder="请输入统一社会信用代码"
              v-model="createForm.credit_code"
              clearable
              :disabled="fact"
            ></el-input>
          </el-form-item>

          <div class="dfa row-main2">
            <el-form-item label="主联系人" prop="contacts" :rules="$rule.required">
              <el-input placeholder="请输入联系人姓名" v-model="createForm.contacts" clearable></el-input>
            </el-form-item>
            <el-form-item labelWidth="0" prop="phone" :rules="$rule.mobile" class="ml20">
              <el-input placeholder="请输入联系人手机号" maxlength="11" v-model="createForm.phone" clearable></el-input>
            </el-form-item>
          </div>

          <template v-for="(item, index) in createForm.else_contacts">
            <div class="dfa">
              <div class="dfa row-main2">
                <el-form-item label="其他联系人" :prop="'else_contacts.' + index + '.contacts'">
                  <el-input v-model="item.contacts" placeholder="请输入联系人姓名" clearable></el-input>
                </el-form-item>
                <el-form-item
                  labelWidth="0"
                  :prop="'else_contacts.' + index + '.phone'"
                  :rules="$rule.checkmobile"
                  class="ml20"
                >
                  <el-input v-model="item.phone" placeholder="请输入联系人手机号" maxlength="11" clearable></el-input>
                </el-form-item>
              </div>
              <div class="row-aside req">
                <el-button @click="rowAdd" type="primary" size="mini">增加</el-button>
                <el-button
                  @click="rowDelete(index)"
                  type="primary"
                  size="mini"
                  :disabled="createForm.else_contacts.length < 2"
                >删除</el-button>
              </div>
            </div>
          </template>

          <el-form-item label="主营产品" prop="main_product">
            <el-tag
              :key="index"
              v-for="(tag, index) in createForm.main_product"
              closable
              :disable-transitions="false"
              @close="handleClose(index)"
            >{{ tag }}</el-tag>
            <el-input
              class="input-new-tag"
              v-if="inputVisible"
              v-model="inputValue"
              ref="saveTagInput"
              size="small"
              @keyup.enter.native="handleInputConfirm"
              @blur="handleInputConfirm"
            ></el-input>
            <el-button v-else class="button-new-tag" size="small" @click="showInput">添加</el-button>
          </el-form-item>

          <el-form-item label="申请技术对接" prop="interface_docking">
            <el-switch v-model="createForm.interface_docking" :active-value="1" :inactive-value="0"></el-switch>（我们将会为您提供凯茵样品商城开放平台接口文档，通过技术对接实现产品发布、发货单推送、库存变更等功能。）
          </el-form-item>

          <el-form-item label="营业执照" prop="license" :rules="$rule.required">
            <el-upload
              action="/api/Common/upload"
              list-type="picture-card"
              :limit="limit"
              :http-request="$.user.upload"
              :file-list="license"
              :on-success="(e) => handleSuccess(e, 'license')"
              :on-remove="(e) => handleRemove(e, 'license')"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <span>请上传小于3m的jpg、png图片</span>
          </el-form-item>

          <el-form-item label="平台入驻协议" prop="agreement" :rules="$rule.required">
            <el-upload
              action="/api/Common/upload"
              list-type="picture-card"
              :limit="limit"
              :http-request="$.user.upload"
              :file-list="agreement"
              :on-success="(e) => handleSuccess(e, 'agreement')"
              :on-remove="(e) => handleRemove(e, 'agreement')"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
            <p>请上传盖有贵单位公章的平台入驻协议照片</p>
            <a href="https://yangpin.shop/平台入驻协议11月最新版20220216.docx" class="btn mt20">下载协议</a>
          </el-form-item>
        </div>

        <!-- 基本资料 end -->

        <!-- 财务信息 start -->
        <div class="bar">财务信息</div>
        <div class="contents">
          <template v-for="(item, index) in createForm.finance">
            <div class="dfa list1">
              <div class="row-main card">
                <el-form-item
                  label="账户类型"
                  :prop="'finance.' + index + '.mold'"
                  :rules="$rule.required"
                >
                  <el-radio
                    class="inp"
                    v-for="(item2, i) in financeMold"
                    v-model="item.mold"
                    :key="i"
                    :label="item2.value"
                    :value="item2.label"
                  >{{ item2.label }}</el-radio>
                </el-form-item>
                <el-form-item
                  label="开户名称"
                  :prop="'finance.' + index + '.account_name'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.account_name" placeholder="请输入开户名称" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="开户银行"
                  :prop="'finance.' + index + '.account_bank'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.account_bank" placeholder="请输入开户银行" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="开户账户"
                  :prop="'finance.' + index + '.account'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.account" placeholder="请输入开户账户" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="电话"
                  :prop="'finance.' + index + '.phone'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.phone" maxlength="11" placeholder="请输入电话" clearable></el-input>
                </el-form-item>
                <el-form-item label="行号" :prop="'finance.' + index + '.card_no'">
                  <el-input v-model="item.card_no" placeholder="请输入行号" clearable></el-input>
                </el-form-item>
                <el-form-item label="备注" :prop="'finance.' + index + '.msg'">
                  <el-input v-model="item.msg" placeholder="请输入备注" clearable></el-input>
                </el-form-item>
              </div>
              <div class="row-aside">
                <el-button @click="financeAdd" type="primary" size="mini">增加</el-button>
                <el-button
                  @click="financeDelete(index)"
                  type="primary"
                  size="mini"
                  :disabled="createForm.finance.length < 2"
                >删除</el-button>
              </div>
            </div>
          </template>
        </div>
        <!-- 财务信息 end -->

        <!-- 财务信息 start -->
        <div class="bar">地址管理</div>
        <div class="contents">
          <template v-for="(item, index) in createForm.address">
            <div class="dfa list1">
              <div class="row-main card">
                <el-form-item
                  label="地址类型"
                  :prop="'address.' + index + '.mold'"
                  :rules="$rule.required"
                >
                  <el-select v-model="item.mold" placeholder="请选择地址类型">
                    <el-option
                      v-for="(item2, i) in addressMold"
                      :key="item2.value"
                      :label="item2.label"
                      :value="item2.value"
                    ></el-option>
                  </el-select>
                </el-form-item>

                <el-form-item
                  label="地址名称"
                  :prop="'address.' + index + '.address_name'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.address_name" placeholder="请输入地址名称（如：液体退货仓）" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="联系人"
                  :prop="'address.' + index + '.contacts'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.contacts" placeholder="请输入联系人" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="联系电话"
                  :prop="'address.' + index + '.phone'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.phone" maxlength="11" placeholder="请输入联系电话" clearable></el-input>
                </el-form-item>
                <el-form-item
                  label="省市区"
                  :prop="'address.' + index + '.areas'"
                  :rules="$rule.required"
                >
                  <el-cascader
                    size="small"
                    :props="countryprop"
                    collapse-tags
                    :options="regionData"
                    v-model="item.areas"
                    @change="
                      (e) => {
                        handleRegion(e, index);
                      }
                    "
                  ></el-cascader>
                </el-form-item>

                <el-form-item
                  label="详细地址"
                  :prop="'address.' + index + '.detail'"
                  :rules="$rule.required"
                >
                  <el-input v-model="item.detail" placeholder="请输入详细地址" clearable></el-input>
                </el-form-item>
                <el-form-item label="备注" :prop="'address.' + index + '.msg'">
                  <el-input v-model="item.msg" placeholder="请输入备注" clearable></el-input>
                </el-form-item>
              </div>
              <div class="row-aside">
                <el-button @click="addressAdd" type="primary" size="mini">增加</el-button>
                <el-button
                  @click="addressDelete(index)"
                  type="primary"
                  size="mini"
                  :disabled="createForm.address.length < 2"
                >删除</el-button>
              </div>
            </div>
          </template>
        </div>
        <!-- 财务信息 end -->

        <template v-if="!supplierAuth">
          <div class="btn-tools">
            <el-button @click="handleCancel" size="medium">取消</el-button>
            <el-button @click="handleSave" type="primary" size="medium" :disabled="disabled">保存</el-button>
          </div>
        </template>
      </el-form>
    </div>
  </div>
</template>

<script>
let financeStr = JSON.stringify({
  mold: '', // 账号类型
  account_name: '', // 开户名称
  account_bank: '', //  开户银行
  account: '', //  开户账户
  phone: '', //  手机号
  card_no: '', //  行号
  msg: '', //  备注
})

let addressStr = JSON.stringify({
  id: '', // id 空为新增
  mold: '', // 地址类型
  address_name: '', //  地址名称
  contacts: '', //  联系人
  phone: '', //  联系电话
  areas: [], //
  province: '', // 区域-省
  city: '', // 区域-市
  district: '', // 区域-区
  detail: '', //  详细地址
  msg: '', //  备注
})
import { mapGetters } from 'vuex'

export default {
  computed: {
    ...mapGetters(['supplierAuth']),
  },
  data() {
    return {
      tabs: [
        { name: 'basic', label: '基础资料' },
        { name: 'finance', label: '财务信息' },
        { name: 'address', label: '地址管理' },
      ],
      currentIndex: 0,
      currentTab: 'basic',
      currentLabel: '基础资料',

      id: '',
      createForm: {
        supplier_id: '', // 供应商id
        classify_id: '', // classify_id
        name: '', // 供应商名称
        credit_code: '', // 统一社会信用代码
        interface_docking: 0,
        contacts: '', // 主联系人
        phone: '', // 主联系人手机号
        authenticity: 1, // 0关闭，1开启
        search_key: '', // 开启的话 要带上启信宝接口返回的这个字段
        else_contacts: [
          // 其他联系人[数组]
          { contacts: '', phone: '' },
        ],
        main_product: [], // 主营产品[数组]
        license: '', // 营业执照 url地址
        agreement: '', // 平台入驻协议 url地址
        finance: [
          // 财务信息[数组，参照以下子参数]
          JSON.parse(financeStr),
        ],
        address: [
          // 地址管理
          JSON.parse(addressStr),
        ],
      },

      financeMold: [], // 财务信息 - 账户类型
      classify: [], // 供应商类型
      addressMold: [], // 地址管理-地址类型

      warns: [0],

      regionData: [],
      countryprop: {
        value: 'value',
        label: 'label',
        expandTrigger: 'hover',
      },
      regionProps: { multiple: true },

      facticity: 0, // 真实性验证
      fact: false,

      qxoptions: [],
      loading: false,

      limit: 1,

      license: [], // 营业执照
      agreement: [], // 入驻协议
      licenses: [], // 营业执照
      agreements: [], // 入驻协议

      disabled: false,

      inputVisible: false,
      inputValue: '',

      info: false,
    }
  },
  created() {
    let that = this
    let { id, statu = 0 } = this.$route.query

    console.log(statu)

    if (statu == 2) {
      that.info = true
    }

    that.id = id
    that.createForm.supplier_id = id
    that.handleInit()
  },

  mounted() {},

  beforeDestroy() {
    console.log('离开')
    // this.$store.dispatch("tagsView/delView", this.$route);
  },

  methods: {
    // 主营产品
    handleClose(tag) {
      this.createForm.main_product.splice(
        this.createForm.main_product.indexOf(tag),
        1
      )
    },
    showInput() {
      console.log(2)
      this.inputVisible = true
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    handleInputConfirm() {
      console.log(3)
      let inputValue = this.inputValue
      if (inputValue) {
        // this.createForm.main_product.push(inputValue);
        this.createForm.main_product[this.createForm.main_product.length] =
          inputValue
      }
      this.inputVisible = false
      this.inputValue = ''
    },

    // 真实性验证
    changeSwitch(e) {
      console.log(e)
      let that = this
      // that.facticity = e===1;
      that.fact = e === 1
      that.createForm.authenticity = e
    },

    async remoteMethod(e) {
      console.log(e)
      if (!!e) {
        let that = this
        that.loading = true
        let { result } = await that.$.supplier.checkQixin({ name: e })
        this.loading = false

        console.log(result)

        let o = []
        result.list.forEach((cur) => {
          o.push({
            label: cur.name,
            value: cur.eid,
          })
        })
        that.qxoptions = o
        that.createForm.search_key = result.search_key
      } else {
        this.qxoptions = []
      }
    },
    supSelectChange(e) {
      console.log(e)
      console.log(this.qxoptions)
      console.log(this.fact)
      let fil = this.qxoptions.filter((cur) => cur.value === e)
      console.log(fil)
      this.createForm.name = fil[0]['label']
    },

    async handleSelect(e) {
      console.log(e)
      let that = this
      if (that.fact) {
        let { result } = await that.$.supplier.checkQixin({
          name: that.createForm.name,
        })
        console.log(result)
      }
    },

    async handleInit() {
      const that = this

      // 供应商信息字典
      let { result } = await that.$.supplier.supplierDict()
      console.log(result)
      that.classify = result.classify // 供应商类型
      that.financeMold = result.finance_mold // 财务信息 - 账户类型
      that.addressMold = result.address_mold // 地址管理-地址类型

      // 供应商详情
      let supres = await that.$.supplier.supplierInfo()
      supres = JSON.parse(JSON.stringify(supres.result))
      console.log(supres)

      let { address, finance, else_contacts, license, agreement } = supres
      // 地址信息
      if (address.length < 1) {
        address.push(JSON.parse(addressStr))
      }
      // 财务信息
      if (finance.length < 1) {
        finance.push(JSON.parse(financeStr))
      }

      // 其他联系人
      if (else_contacts.length < 1) {
        else_contacts.push({ contacts: '', phone: '' })
      }

      // 营业执照和平台入驻协议
      if (!!license) {
        let lic = license.lastIndexOf('/') + 1
        let licname = license.slice(lic)
        that.license = that.licenses = [{ name: licname, url: license }]
      }
      if (!!agreement) {
        let agr = agreement.lastIndexOf('/') + 1
        let agrname = agreement.slice(agr)
        that.agreement = that.agreements = [{ name: agrname, url: agreement }]
      }

      supres.supplier_id = supres.id
      delete supres.id

      console.log(supres)
      supres.authenticity = 1
      that.fact = true

      //区域回显
      supres.address.forEach((curr) => {
        curr['areas'] = []
        if (curr.province != 0) {
          curr['areas'].push(curr.province)
          if (curr.city != 0) curr['areas'].push(curr.city)
          if (curr.district != 0) curr['areas'].push(curr.district)
        }
      })
      console.log(supres)
      supres.classify_id = supres.classify_id === 0 ? '' : supres.classify_id
      that.regionData = await that.$util.regionData(that, 3) // 省市区
      that.createForm = supres
    },

    handleToggle(e) {
      let that = this
      if (e != that.currentIndex) {
        that.currentIndex = e
        that.currentLabel = that.tabs[e]['label']
        that.currentTab = that.tabs[e]['name']
        that.license = that.licenses
        that.agreement = that.agreements
      }
    },

    // 其他联系人
    rowAdd() {
      console.log('rowAdd')
      let that = this
      that.createForm.else_contacts.push({ contacts: '', phone: '' })
    },
    rowDelete(e) {
      console.log('rowDelete')
      this.createForm.else_contacts.splice(e, 1)
    },

    // 图片上传
    handleSuccess(e, k) {
      let that = this
      let p = e.result.path
      let lt = p.lastIndexOf('/') + 1
      let name = p.slice(lt)

      that[k + 's'].push({ name, url: p })
      that.createForm[k] = p
    },

    // 图片删除
    handleRemove(e, k) {
      console.log(e, k)
      let that = this
      let { url } = e
      let lists = that[k + 's']
      console.log(lists)
      lists.some((cur, i) => {
        if (cur.url == url) {
          lists.splice(i, 1)
          return true
        }
      })
      that[k] = that[k + 's'] = lists
    },

    // 财务信息 添加 & 删除
    financeAdd() {
      this.createForm.finance.push(JSON.parse(financeStr))
    },
    financeDelete(e) {
      this.createForm.finance.splice(e, 1)
    },

    // 地址信息 添加 & 删除
    addressAdd() {
      this.createForm.address.push(JSON.parse(addressStr))
    },
    addressDelete(e) {
      this.createForm.address.splice(e, 1)
    },

    // 省市区
    handleRegion(value, index) {
      this.$util.ext(this.createForm.address[index], {
        province: value[0],
        city: value[1] ?? 0,
        district: value[2] ?? 0,
      })
    },

    // 取消
    handleCancel(e) {
      console.log(e)
    },

    handleSave() {
      const that = this
      console.log(that.createForm)
      that.$refs.createForm.validate(async (v) => {
        if (!v) {
          that.$message({ type: 'error', message: '填写有误' })
          return false
        }
        // supAction

        let cf = JSON.parse(JSON.stringify(that.createForm))
        cf.address.forEach((curr) => {
          delete curr.areas
        })

        let conts = []
        cf.else_contacts.forEach((curr) => {
          if (!!curr.contacts && !!curr.phone) {
            conts.push(curr)
          }
          delete curr.areas
        })
        cf.else_contacts = conts

        try {
          that.disabled = true
          let { result } = await that.$.supplier.supplierAction(cf)
          that.$message({ type: 'success', message: '提交成功' })
          that.$store.dispatch('tagsView/delView', this.$route)
          that.$router.push(`/dashboard`)
          console.log(result)
        } catch (e) {
          that.disabled = false
        }
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.contents {
  background-color: #fff;
  padding-right: 20px;
}

.contents .list1 {
  border-bottom: 1px solid #f0f0f8;
}

.contents .list1:last-of-type {
  border-bottom: none;
}

.card {
  //margin-right: 50px;
  margin-bottom: 0;
  padding-bottom: 0;
}

.supname {
  height: 32px;
  margin-bottom: 18px;
  margin-left: 100px;
}

.label {
  margin-right: 20px;
}

.btn-fact {
  margin: 0 0 18px 20px;
}

.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.bar {
  position: relative;
  padding-left: 15px;
  background-color: rgba(193, 193, 193, 0.8);
  line-height: 50px;
  margin-top: 20px;
  font-size: 18px;
  font-weight: 600;
}

.bar:before {
  content: '';
  position: absolute;
  width: 2px;
  top: 0;
  bottom: 0;
  left: 0;
  background-color: #16d585;
}

.contents1 {
  padding: 20px 20px 20px 0;
}

.req {
  margin-left: 20px;
}
</style>
